package com.suncaper.shop.controller;

import com.suncaper.shop.domain.*;
import com.suncaper.shop.service.CartService;
import com.suncaper.shop.service.ProductService;
import com.suncaper.shop.service.WishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Controller
public class WishController {


    @Autowired
    private WishService wishService;

    @Autowired
    private ProductService productService;

    @Autowired
    private CartService cartService;

    @PostMapping("/wish/add")
    @ResponseBody
    public String addToWIsh(@RequestParam("pid") Integer pid,
                            HttpSession session,
                            Map<String, Object> map) {
        if (session.getAttribute("userInfo") == null) {
            map.put("msg", "请先登录");
            return "createaccount";
        }
        Integer uid = ((User) session.getAttribute("userInfo")).getId();
        wishService.addToWish(pid, uid);
        return "index";
    }

    @RequestMapping(value = {"/wishlist", "/wishlist.html"})
    public String wish(HttpSession session, Model model) {
        if (session.getAttribute("userInfo") != null) {
            List<Wish> list = wishService.getAllWishList(((User) session.getAttribute("userInfo")).getId());
            model.addAttribute("wish", list);
        }

        return "wishlist";
    }


    @GetMapping("/wish/delete")
    @ResponseBody
    public Boolean deleteItem(@RequestParam("pid") Integer pid,
                              HttpSession session, Model model) {
        wishService.deleteFromWish(pid);
        return true;
    }

    @PostMapping("/wishCart/add")
    public String WishaddToCart(@RequestParam("pid") Integer pid,
                                @RequestParam("count") Integer count,
                                HttpSession session,
                                Model model) {

        Product product = productService.findByPid(pid);
        Cart cart = cartService.addToCart(count, product, session);
        Collection<CartItem> cartItems = cart.getCartItems();
        cartService.addCartView(session, model, cart, cartItems);
        wishService.deleteFromWish(pid);
        return "redirect:/cart";
    }

}
